/**
 * Created by commy on 2015/5/1.
 */
var mongodb = require('mongodb'),
    cache = {};

function connect(url,options){
    var fns = [],status = 0, _db = cache[url];
    return function (f){
        var args = arguments;
        if(_db !== null && typeof  _db === 'object'){
            f.call(null,_db);
            return;
        }
        fns.push(f);
        if(status === 0){
            status = 1;
            mongodb.MongoClient.connect(url,options,function(err,db){
                if(err){throw err;}
                _db = cache[url] = db;
                for(var i = 0,len = fns.length;i <len;i++){
                    fns.shift().call(null,_db);
                }
            });
        }
    };
}


var url = 'mongodb://localhost:27017/test';
if(process.env.NODE_ENV=='production') url = 'mongodb://9b46573d-d168-475e-b235-c51dbb4204e6:9LaMrpdJ1FHXHsKRPQRYLg@10.9.27.25:27017/552c2a72-d415-43f8-9bba-eaf8f4d32c4b';
module.exports = connect(url,null);